//
//  GYXHomeViewController.swift
//  GYXWeibo
//
//  Created by Twisal on 2016/11/8.
//  Copyright © 2016年 Twisal. All rights reserved.
//

import UIKit

/// cellid
fileprivate let normalCellId = "normalCellId"
fileprivate let retweetedCellId = "retweetedCellId"

// MARK: - HOME控制器
class GYXHomeViewController: GYXBaseViewController {

    /// 微博列表模型
    fileprivate lazy var listViewModel = GYXStatusListViewModel()

    
    /// 显示好友控制器
    func showFriends(){
        print(#function)
        let demoVc = GYXDemoViewController()
        navigationController?.pushViewController(demoVc, animated: true)
    }
    
    /// 加载数据
    override func loadData() {
        /*************模拟异步加载数据***********/
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
//
//            for i in 0..<15 {
//
//                if self.isPullup {
//                    self.statusList.append("上拉\(i)")
//                } else {
//                    self.statusList.insert(i.description, at: 0)
//                }
//            }
//            print("加载数据结束")
//            self.isPullup = false
//            self.refreshControl?.endRefreshing()
//            self.tableView?.reloadData()
//        }

        /*************直接使用get方法获取数据***********/
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let params = ["access_token" : "2.00HNQp6BeAFyLDaf67d87d1a0vWS8U"]
//        GYXNetworkManager.shared.get(urlString, parameters: params, progress: nil, success: { (_, json) in
//            print("\(json)");
//        }) { (_, error) in
//            print("加载错误\(error)")
//        }
        
        /*************使用第一次封装进行请求***********/
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let params = ["access_token" : "2.00HNQp6BeAFyLDaf67d87d1a0vWS8U"]
//        GYXNetworkManager.shared.request(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
//            print("当前数据为: \(json)")
//        }
        
        /*************使用第二次封装进行请求***********/
//        GYXNetworkManager.shared.loadStatusList { (statuses, isSuccess) in
//            print("当前数据为: \(statuses ?? nil)")
//        }
        
        /*************将业务逻辑封装到ViewModel中进行请求***********/
        print("准备刷新,最后一条微博数据为:\(self.listViewModel.statusList.last?.status.text)")
        listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
            print("加载数据结束")
            self.isPullup = false
            self.refreshControl?.endRefreshing()
            if shouldRefresh {
                self.tableView?.reloadData()
            }
        }
        

    }
    
    // MARK: - 事件监听
    /// 导航条title按钮点击事件
    ///
    /// - Parameter btn: 被点击的button
    @objc fileprivate func titleBtnClick(btn: UIButton) {
        btn.isSelected = !btn.isSelected
    }

}

// MARK: - 页面布局
extension GYXHomeViewController {
    
    /// 初始化tableView
    override func setupTableView() {
        super.setupTableView()
        naviItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        tableView?.register(UINib(nibName: "GYXStatusNormalCell", bundle: nil), forCellReuseIdentifier: normalCellId)
        tableView?.register(UINib(nibName: "GYXStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
//        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        tableView?.separatorStyle = .none
        setupNaviTitleView()
    }
    
    
    /// 初始化导航条titleView
    private func setupNaviTitleView() {
        
        let title = GYXNetworkManager.shared.userAccount.screen_name
        let btn = GYXTitleButton(title: title)
        naviItem.titleView = btn
        btn.addTarget(self, action: #selector(titleBtnClick), for: .touchUpInside)
    }
    
    
}


// MARK: - GYXStatusCellDelegate
extension GYXHomeViewController: GYXStatusCellDelegate {
    /// 实现cell的代理方法
    func statusCellDidSelectedURLString(cell: GYXStatusCell, urlString: String) {
        let vc = GYXWebViewController()
        vc.urlString = urlString
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - UITableViewDataSource
extension GYXHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 0,获取数据模型
        let viewModel = listViewModel.statusList[indexPath.row]
        // 1,取不同的cell
        let cellId = (viewModel.status.retweeted_status == nil) ? normalCellId : retweetedCellId
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! GYXStatusCell
        // 2,为cell赋值
        cell.viewModel = viewModel
        // 3,设置代理
        cell.delegate = self
        // 3,返回cell
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let vm = listViewModel.statusList[indexPath.row]
        return vm.rowHeight
    }

}
